﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessLogic;
using System.Web.Security;
using System.Data;

public partial class Admin_ConstituentManagement : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            SetGridViewSettings();
            ClientScript.RegisterStartupScript(this.GetType(), "ModalPopup", "function showModal() { $find('ShowModal').show(); }", true);
            BindGridView();
            BindDropDownLists();           
        }
        else
        {
            string target = Request.Form["__EVENTTARGET"];
            string argument = Request.Form["__EVENTARGUMENT"];

            if (target.Equals(updatePanelConstituents.ClientID))
            {
                BindGridView();                
            }
        }
    }

    private void SetGridViewSettings()
    {
        var pageSize = string.Empty;
        var searchText = string.Empty;
        var pageIndex = 0;

        if (Request.QueryString["pageSize"] != null)
        {
            pageSize = Request.QueryString["pageSize"].ToString();
        }

        if (Request.QueryString["searchText"] != null)
        {
            searchText = Request.QueryString["searchText"].ToString();
        }

        if (Request.QueryString["pageIndex"] != null)
        {
            if(!int.TryParse(Request.QueryString["pageIndex"], out pageIndex))
            {
                pageIndex = 0;
            }
        }

        txtConstituentSearch.Text = searchText;
        ddlPageSize.SelectedValue = pageSize;
        grvConstituents.PageIndex = pageIndex;
    }

    private void BindGridView()
    {
        var pageIndex = 0;

        if (Request.QueryString["pageIndex"] != null)
        {
            if (!int.TryParse(Request.QueryString["pageIndex"], out pageIndex))
            {
                pageIndex = 0;
            }
        }

        BindGridView(pageIndex, string.Empty);
    }

    private void BindGridView(int pageIndex)
    {
        BindGridView(pageIndex, string.Empty);
    }
    
    private void BindGridView(string sortExpression)
    {
        BindGridView(0, sortExpression);
    }

    private void BindGridView(int pageIndex, string sortExpression)
    {
        string searchText = txtConstituentSearch.Text;

        grvConstituents.PageSize = Convert.ToInt16(ddlPageSize.SelectedValue);
        
        var fromBack = false;

        if(Request.QueryString["FROMBACK"] != null)
        {
            if(!bool.TryParse(Request.QueryString["FROMBACK"], out fromBack))
            {
                fromBack = false;
            }
        }

        DataTable dt = null;

        if (ViewState["ORIGINALSEARCHDATATABLE"] == null || fromBack)
        {
            dt = Constituent.GetActivePrimariesDataTable(searchText); 
            ViewState["ORIGINALSEARCHDATATABLE"] = dt;
        }

        if(dt == null)
        {
            dt = Constituent.GetActivePrimariesDataTable(searchText, (DataTable)ViewState["ORIGINALSEARCHDATATABLE"]);
        }
                
        if(!string.IsNullOrWhiteSpace(sortExpression))
        {
            dt.DefaultView.Sort = sortExpression + " " + GetSortDirection(sortExpression, grvConstituents.ID);
        }

        grvConstituents.DataSource = dt;
        grvConstituents.PageIndex = pageIndex;
        grvConstituents.DataBind();        
    }

    protected void linkButton1_OnClick(object sender, EventArgs e)
    {
        LinkButton lb = (LinkButton)sender;

        if(lb != null)
        {
            var pageSize = ddlPageSize.SelectedItem.Value;
            var searchText = txtConstituentSearch.Text;
            var id = lb.CommandArgument;
            var pageIndex = grvConstituents.PageIndex;
            var url = "~/Admin/ConstituentInformation.aspx?id={0}&pageSize={1}&searchText={2}&pageIndex={3}";        
        
            Response.Redirect(string.Format(url, id, pageSize, searchText, pageIndex)); 
        }
    }   

    protected void grvConstituents_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        BindGridView(e.NewPageIndex);
    }

    protected void grvConstituents_OnSorting(object sender, GridViewSortEventArgs e) 
    {
        BindGridView(e.SortExpression);
    }

    private string GetSortDirection(string column, string gridViewName)
    {
        string sortExpressionName = gridViewName + "SortExpression";
        string sortDirectionName = gridViewName + "SortDirection";

        // By default, set the sort direction to ascending.
        string sortDirection = "ASC";

        // Retrieve the last column that was sorted.
        string sortExpression = ViewState[sortExpressionName] as string;

        if (sortExpression != null)
        {
            // Check if the same column is being sorted.
            // Otherwise, the default value can be returned.
            if (sortExpression == column)
            {
                string lastDirection = ViewState[sortDirectionName] as string;
                if ((lastDirection != null) && (lastDirection == "ASC"))
                {
                    sortDirection = "DESC";
                }
            }
        }

        // Save new values in ViewState.
        ViewState[sortDirectionName] = sortDirection;
        ViewState[sortExpressionName] = column;

        return sortDirection;
    }
    
    private void BindDropDownLists()
    {
        Common.Utility.BindDropDownList<AddressType>(ddlAddressType, MyCache.GetCodeTableCache<AddressType>(), SEPDefaults.Other.AddressType);
        Common.Utility.BindDropDownList<EmailType>(ddlEmailType, MyCache.GetCodeTableCache<EmailType>(), SEPDefaults.Other.EmailType);
        Common.Utility.BindDropDownList<PhoneType>(ddlPhoneType, MyCache.GetCodeTableCache<PhoneType>(), SEPDefaults.Other.PhoneType);
        Common.Utility.BindDropDownList<State>(ddlState, MyCache.GetCodeTableCache<State>(), SEPDefaults.Other.State);  
        Common.Utility.BindDropDownList<Country>(ddlCountry, MyCache.GetCodeTableCache<Country>(), SEPDefaults.Other.CountryAbbreviation, "ABBREVIATION", "ID");     
    }

    //protected void DeleteRecord(object sender, GridViewDeleteEventArgs e)
    //{
    //    Guid id = new Guid(grvConstituents.DataKeys[e.RowIndex].Value.ToString());

    //    if (Guid.Empty != id)
    //    {
    //        Constituent constituent = new Constituent();
    //        constituent.ID = id;
    //        constituent.Delete();
    //    }

    //    this.BindGridView();
    //}

    protected void RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            LinkButton l = (LinkButton)e.Row.FindControl("LinkButton1");
            l.Attributes.Add("onclick", "javascript:return confirm('Really delete this constituent?')");
        }
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        SaveNewConstituent();
    }

    private void SaveNewConstituent()
    {
        //this happens when they click "save" on the modal form
        //hide the form first so it seems quicker in the front end
        modalNewConstituent.Hide();

        //grab the constituent they entered and create them
        Constituent con = ConstituentFromModalForm();
        
        //List<Constituent> dupes = Constituent.CheckForDuplicate(con);

        if(con.Create())
        {
            //clear the data they just entered to get ready for next time
            ClearControlsOnContainer(pnlNewGuest);

            //refresh the grid
            BindGridView();            

            lblConstituentError.Visible = false;
        }
        else
        {
            lblConstituentError.Visible = true;
            lblConstituentError.Text = SEPDefaults.ErrorMessages.GENERIC;
        }
    }

    private List<string> Prefixes()
    {
        List<string> prefixes = new List<string>();
        prefixes.Add("The");

        //return them all as uppercase for comparison
        return prefixes.ConvertAll(x => x.ToUpper());
    }

    /// <summary>
    /// Translates the data entered on the modal form into a constituent object
    /// </summary>
    /// <returns>A fully formed constituent based on data from the modal popup</returns>
    private Constituent ConstituentFromModalForm()
    {
        try
        {
            Constituent constituent = new Constituent();
            string firstname = string.Empty;

            constituent.IsOrganization = chkIsOrganization.Checked;
            constituent.FirstName = (constituent.IsOrganization ? string.Empty : txtFirstName.Text);   //no first name for orgs
            constituent.LastName = (constituent.IsOrganization ? txtOrganizationName.Text : txtLastName.Text);
            constituent.LastNamePrefix = (constituent.IsOrganization ? LastNamePrefixFromLastName(txtOrganizationName.Text) : string.Empty);  //no last name prefix for individuals
            constituent.IsPrimary = true;
            constituent.Address = AddressFromModalPopup();
            constituent.Phone = PhoneFromModalPopup();
            constituent.EmailAddress = EmailFromModalPopup();

            return constituent;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    private string LastNamePrefixFromLastName(string lastname)
    {
        string firstword = lastname.Split(' ')[0];
        if (Prefixes().Any(str => str.Contains(firstword.ToUpper())))
        {
            return firstword;
        }
        else
        {
            return string.Empty;
        }
    }

    private Address AddressFromModalPopup()
    {
        Address address = new Address();
        address.AddressBlock = txtAddress.Text;
        address.City = txtCity.Text;

        State s = new State();
        s.ID = new Guid(ddlState.SelectedValue);

        address.State = s;

        Country c = new Country();
        c.ID = new Guid(ddlCountry.SelectedValue);

        address.Country = c;
        address.PostCode = txtZip.Text;

        AddressType at = new AddressType();
        at.ID = new Guid(ddlAddressType.SelectedValue);

        address.AddressType = at;

        return address;
    }

    private Email EmailFromModalPopup()
    {
        if (!string.IsNullOrWhiteSpace(txtEmail.Text))
        {
            Email em = new Email();
            em.EmailAddress = txtEmail.Text;

            EmailType et = new EmailType();
            et.ID = new Guid(ddlEmailType.SelectedValue);

            em.EmailAddressType = et;
            return em;
        }
        else
        {
            return null;
        }
    }

    private Phone PhoneFromModalPopup()
    {
        if (!string.IsNullOrWhiteSpace(txtPhone.Text))
        {
            Phone phone = new Phone();
            phone.Number = txtPhone.Text;
            phone.Extension = txtExtension.Text;
            phone.IsPrimary = true;

            PhoneType pt = new PhoneType();
            pt.ID = new Guid(ddlPhoneType.SelectedValue);
            phone.PhoneType = pt;

            return phone;
        }
        else
        {
            return null;
        }
    }

    private void ClearControlsOnContainer(Control container)
    {
        //we hit this code, but the textboxes dont actually get reset.
        //may have to do it from javascript, since the "Save" button never posts back.
        foreach (Control c in container.Controls)
        {
            if (c is TextBox)
            {
                ((TextBox)c).Text = string.Empty;
            }
            else if (c is CheckBox)
            {
                ((CheckBox)c).Checked = false;
            }
            else if (c is DropDownList)
            {
                ((DropDownList)c).ClearSelection();
            }
        }
    }

    protected void btnNewConstituent_Click(object sender, EventArgs e)
    {
        pnlNewGuest.Visible = true;
        modalNewConstituent.Show();
    }
}
